package com.atguigu.interactive;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


//这个版本是Lock+              condition.await()+            condition.signalAll()

class Car{
    private  int car = 0;

    Lock lock =new ReentrantLock();
    Condition condition = lock.newCondition();

    public void up(){
        lock.lock();
        try {
            while (car != 0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+(++car));
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void down(){
        lock.lock();
        try {
            while (car == 0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+(--car));
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

public class ProdConsumerDemoV2 {
    public static void main(String[] args) {
        Car car = new Car();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                car.up();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                car.down();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                car.up();
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                car.down();
            }
        },"D").start();
    }
}
